
cc.Class({
    extends: require('UI-PanelWindow'),

    properties: {
        content :cc.Node,
        scrollView :cc.ScrollView,
        chatLeftItem : cc.Prefab,
        chatRightItem : cc.Prefab,
        editBox : cc.EditBox
    },

    onLoad(){
        this._super();
        this.messages = [];
    },

    onEnable(){
        this._super();
        this.scrollView.node.on("bounce-top", this.scorllToTop, this);
        this.scrollView.node.on("bounce-bottom", this.scrollToBottom, this);
        this.schedule(()=>{
            this.updateMessage();
        },2.0);
    },


    scorllToTop(){
        var obj = {
            _id : this._id
        }
        if(this.messages && this.messages.length>0){
            obj.lastId = this.messages[this.messages.length-1].chatIndex
        }
        var self = this
        this.httpGet('/game/chat','privateChat.msg',obj,function(err,res){
            if(err || res.messages.length ==0){
                return;
            }
            self.messages = self.messages.concat(res.messages);
            self.addMessageToTop();
        })
        
    },

    scrollToBottom(){
        this.updateMessage(true);
    },

    onDisable(){
        this.scrollView.node.off("bounce-top", this.scorllToTop, this);
        this.scrollView.node.off("bounce-bottom", this.scrollToBottom, this);
    },

    addMessageToBottom(toBottom){
        var offset = this.scrollView.getScrollOffset();
        var maxoffset = this.scrollView.getMaxScrollOffset();
        var toBottom1 = toBottom || Math.abs(maxoffset.y - offset.y)<20;
        var lasttime = 0;
        for(var i=this.messages.length-1; i>=0; i--){
            var msg = this.messages[i];
            if(!msg.isShow){
                
                var node = msg.isSelf? cc.instantiate(this.chatRightItem) : cc.instantiate(this.chatLeftItem);
                var _message=msg.isSelf?this._msg2.user:this._msg1.user;
                node.getComponent('UserInfo').setOptions(_message);
                node.isNew = false;
                cc.find('panel/msg/txt',node).getComponent(cc.Label).string = msg.message.content
                if(msg.time-lasttime > 60*6000){
                    var a = new Date(msg.time);
                    var time = '';
                    if(i != 0){
                        var b = new Date(lasttime);
                        if(a.getFullYear() != b.getFullYear() || a.getMonth() != b.getMonth() || a.getDate() != b.getDate()){
                            time = a.getFullYear()+'-'+a.getMonth()+'-'+a.getDate()+' '
                        }
                    } else {
                        time = a.getFullYear()+'-'+a.getMinutes()+'-'+a.getDate()+' '
                    }
                    time += a.getHours()+':'+a.getMinutes()+':'+a.getSeconds();
                    cc.find('panel/top/time',node).active = true;
                    cc.find('panel/top/time',node).getComponent(cc.Label).string =  time
                }
                
                this.content.addChild(node);
                msg.isShow = true;
            }
            lasttime = msg.time;
        }
        if(toBottom1)
            this.scrollView.scrollToBottom();
    },

    addMessageToTop(){ //从上向下拉，在顶部刷新历史消息
        this.content.removeAllChildren();
        var lasttime = 0;
        for(var i=this.messages.length-1; i>=0; i--){
            var msg = this.messages[i];
            var node = msg.isSelf? cc.instantiate(this.chatRightItem) : cc.instantiate(this.chatLeftItem);
            
            node.isNew = !msg.isShow;
            if(node.isNew)
                node.opacity = 0;  //先隐藏一下，否则会闪一下
            
            if(msg.time-lasttime > 60*6000){
                var a = new Date(msg.time);
                var time = '';
                if(i != 0){
                    var b = new Date(lasttime);
                    if(a.getFullYear() != b.getFullYear() || a.getMonth() != b.getMonth() || a.getDate() != b.getDate()){
                        time = a.getFullYear()+'-'+a.getMonth()+'-'+a.getDate()+' '
                    }
                } else {
                    time = a.getFullYear()+'-'+a.getMonth()+'-'+a.getDate()+' '
                }
                time += a.getHours()+':'+a.getMinutes()+':'+a.getSeconds();
                cc.find('panel/top/time',node).active = true;
                cc.find('panel/top/time',node).getComponent(cc.Label).string =  time
            }
            cc.find('panel/msg/txt',node).getComponent(cc.Label).string = msg.message.content
            this.content.addChild(node);
            msg.isShow = true;
        }

        this.scheduleOnce(()=>{
            var height =0;
            var news = 0;
            var children = this.content.children
            for(var i=0; i<children.length; i++){
                if(children[i].isNew){
                    children[i].runAction(cc.fadeIn(0.2)); //等调好位置先，再慢慢显示
                    height+=children[i].height
                    news++;
                }
                children[i].isNew = false;
            }
            cc.log('height:',news,height);
            this.scrollView.scrollToOffset(cc.v2(0,height-100),0.01);
        },0.01)
    }, 

    updateMessage(toBottom){
        var obj = {
            _id : this._id
        }
        if(this.messages && this.messages.length>0){
            obj.afterId = this.messages[0].chatIndex
        }
        var self = this
        this.httpGet('/game/chat','privateChat.msg',obj,function(err,res){
            if(err || res.messages.length ==0){
                return;
            }
            cc.log('updateMessage:',res);
            self.messages = res.messages.concat(self.messages);
            self.addMessageToBottom(toBottom);
        })
       
    },

    setOptions(options){
        var self = this;
        this.httpGet('/game/gameUser/getInfoById',{},{_id:options._id},function(err,res){
            if(!err) {
                self._msg1=res;
                self._id = options._id;
                self.httpGet('/game/gameUser/getInfoById',{},{_id:global.Data._id},function(err,res){
                    if(!err) {
                        self._msg2=res;
                        self.updateMessage(true);
                    }
                }.bind(this))
            }
        }.bind(this))

    },

    onBtnSend(){
        var d = {
            type : 0,
            _id:this._id,
            message : this.editBox.string
        }
        var self=this;
        this.httpGet('/game/chat','privateChat.send',d,function(err,res){
            self.editBox.string=''
            cc.log('onBtnSend:',res);
        })
    }
});
